
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from django.http import HttpResponse
from rest_framework import status
from io import BytesIO
import random


from PIL import Image,ImageDraw,ImageFont
import redis
import re
import random


from user.models import *
from user.serializer import *

# 短信验证码
class SendCodeView(APIView):
    def post(self,request):
        phone = request.data.get('phone')

        if not re.findall(r"^1[3-9]\d{9}$",phone):
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'请输入正确的手机号'})

        # 生成验证码
        sms_code = random.randint(100000,999999)



# 注册
# class Register(APIView):
#     def post(self,request):


# 生成图片和验证码
def image_code():
    # 通过数字获取ascii表中的对应字母
    def get_char():
        return chr(random.randint(65, 90))

    # 获取随机颜色
    def get_color(*args):
        if args == ():
            return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        while True:
            text_color = get_color()
            aberration = 3 * (text_color[0] - args[0][0]) ** 2 + 4 * (text_color[0] - args[0][1]) ** 2 + 2 * (text_color[0] - args[0][2]) ** 2
            rgb2 = 100000  # 设置字体颜色与背景色差，值越大，字体越清晰，机器人就更容易识别，相对应的代价就是需要随机更多次的RGB值。极端情况验证码字体背景rgb均为128，aberration最小的最大值为147456
            if aberration > rgb2:
                return text_color

    # 创建图片对象
    img_back = get_color()
    img = Image.new(mode='RGB', size=(120, 50), color=img_back)
    # 创建画笔对象
    draw = ImageDraw.Draw(img, mode='RGB')
    # 噪点 xy：基于图片的坐标，fill表示点颜色
    for i in range(50):
        draw.point([random.randint(0, 120), random.randint(0, 50)], fill=get_color())

    # 噪线 xy:(起点坐标，终点坐标) fill：颜色  width：线宽
    # draw.line((50, 30, 100, 60),fill='purple', width=5)
    for i in range(5):
        draw.line([random.randint(0, 120), random.randint(0, 50), random.randint(0, 120), random.randint(0, 50)],
                  fill=get_color())
    # 划圆或弧线
    for i in range(5):
        x = random.randint(0, 120)
        y = random.randint(0, 50)
        x2 = x + 4
        y2 = y + 4

        draw.arc((x, y, x2, y2), 0, 90, fill=get_color())

    font = ImageFont.truetype('fonts/STHUPO.TTF', 30)
    # font = ImageFont.truetype('fonts/STCAIYUN.TTF', 30)

    # 用来拼接验证码字符的
    char_list = []
    for i in range(4):
        char = get_char()
        char_list.append(char)
        height = random.randint(10, 15)
        draw.text([18 * (i + 1), height], char, get_color(img_back), font=font)
    char_code = ''.join(char_list)

    # char_code = ''.join(random.sample(string.digits + string.ascii_letters,4))

    # 模糊效果和边缘增强效果
    # img = img.filter(ImageFilter.BLUR)
    # img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img, char_code


# 图片验证码--接口
class ImagCodeView(APIView):
    def get(self,request,uuid):
        img, char_code = image_code()

        # 将图片数据写到内存
        stream = BytesIO()
        img.save(stream, format='png')

        rds = redis.Redis(db=2)
        rds.setex('%s_imgcode' % uuid, 60 * 5, char_code)

        return HttpResponse(stream.getvalue(), content_type='image/png')


# 登录
# class LoginView(APIView):
#     def post(self,request):
#         account = request.data.get('account')
#         password = request.data.get('password')
#         imgcode = request.data.get('img')
#         uuid = request.data.get('uuid')
#
#         staff = StaffModel.objects.filter(account=account).first()
#
#         if not staff:
#             return Response({'code':500,'msg':'账号错误'})
#
#         if not check_password(password,staff.password):
#             return Response({'code':500,'msg':'密码错误'})
#
#         rds = redis.Redis(db=2)
#         redis_code = rds.get('%s_imgcode'%uuid)
#         # if not redis_code:
#         #     return Response({'code':500,'msg':'验证码已过期'})
#         # if imgcode != redis_code.decode():
#         #     return Response({'code':500,'msg':'验证码输入错误'})
#
#         data = {
#             'id':staff.id,
#             'role_id':staff.role.id,
#         }
#         token = generate_jwt(data)
#
#         role = RoleModel.objects.filter(id=staff.role_id).first()
#         rank = RankModel.objects.filter(id=staff.rank_id).first()
#         job = JobModel.objects.filter(id=staff.job_id).first()
#         department = DepartmentModel.objects.filter(id=staff.department_id).first()
#
#         userinfo = {
#             'id':staff.id,
#             'name':staff.name,
#             'phone':staff.phone,
#             'account':staff.account,
#             'address':staff.address,
#             'birthday':staff.birthday,
#             'head_img':staff.head_img,
#             'role':role.roname,
#             'rank':rank.rname,
#             'job':job.jname,
#             'department':department.dname
#         }
#
#         # 登陆成功后获取ip
#         if request.META.get('HTTP_X_FORWARDED_FOR'):
#             ip = request.META.get('HTTP_X_FORWARDED_FOR')
#         else:
#             ip = request.META.get('REMOTE_ADDR')
#         print('===== ip=================', ip)
#
#         # 设备的信息
#         print(type(request))  # <class 'django.core.handlers.wsgi.WSGIRequest'>
#         system = request.environ.get("HTTP_USER_AGENT")
#         print('设备信息：', system)  # 全部返回的是个字典
#
#         # 获取登陆地址
#         cz = CzIp()
#         places = cz.get_addr_by_ip(ip)
#         print('登陆地址：', places)
#
#         # 加入登录日志
#         try:
#             ConLogModel.objects.create(staff_id=staff.id, ip=ip, account=account, facility=system,
#                                        login_address=places)
#         except Exception as e:
#             print(f'登录日志添加失败{e}')
#
#         return Response({'code':200,'msg':'登录成功','data':userinfo,'token':token})


# 获取轮播图
class CarouselImgView(APIView):
    def get(self,request):
        try:
            showimg = ShowImgModel.objects.filter(is_show=True).all()
            ser = CarouselImgSer(showimg,many=True)
            return Response({'code':status.HTTP_200_OK,'msg':'轮播图获取成功','data':ser.data})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})





